<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * @param $url
 * @param $data
 * @return mixed
 */
function curl($url, $data)
{
    $header[] = "Content-type: application/x-www-form-urlencoded;charset=utf-8";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 获取转向后的内容
    $return_str = curl_exec($curl);
    curl_close($curl);
    return $return_str;
}
/**
 * 生成唯一token
 * @return string
 */
function set_token()
{
    $str = md5(uniqid(md5(microtime(true)), true));  //生成一个不会重复的字符串
    $str = sha1($str);  //加密
    return $str;
}


/**
 * 添加管理员操作记录
 * @param $content
 * @param $type
 * @return bool
 */
function insert_log($content, $type)
{
    $opLog = new \app\admin\model\DailyLog();
    $newData = array();
    $newData['content'] = $content;
    $newData['type'] = $type;
    $newData['admin_id'] = session('admin_id');
    return $opLog->save($newData);
}

/**
* Notes: 检查用户魅力，财富等级
* User: 王俊成
* Date: 2018/10/26
* Time: 10:55
* @param int $exp
* @param string $type
* @return array|bool
    */
function checkRank($exp = 0, $type = 'wealth'){
    //财富
    $wealth = array(0, 1000, 2000, 3000, 4000, 8000, 12000, 16000, 20000, 35000, 50000, 65000, 80000, 140000, 200000, 260000, 320000, 490000, 660000, 830000, 1000000, 2000000, 3000000, 4000000, 5000000, 7000000, 9000000, 11000000, 13000000);
    $charm = array(0, 4000, 20000, 80000, 320000, 1000000, 5000000, 13000000);
    if ($type == 'wealth') {
        if ($exp >= 13000000) {
            $data = array(
                'exp' => $exp,
                'rank' => array_search('13000000', $wealth) + 1,
                'next_rank' => array_search('13000000', $wealth) + 1,
                'differ_exp' => 0,
                'ratio' => 1,
            );
        } else {
            for ($i = 0; $i < count($wealth); $i++) {
                if ($exp < $wealth[$i]) {
                    $num = $i;
                    break;
                }
            }
            $data = array(
                'exp' => $exp,
                'rank' => $num,
                'next_rank' => $num + 1,
                'differ_exp' => $wealth[$num] - $exp,
                'ratio' => floor((($exp - $wealth[$num - 1]) / ($wealth[$num] - $wealth[$num - 1])) * 100) / 100,
            );
        }
    } elseif ($type == 'charm') {
        if ($exp >= 13000000) {
            $data = array(
                'exp' => $exp,
                'rank' => array_search('13000000', $charm) + 1,
                'next_rank' => array_search('13000000', $charm) + 1,
                'differ_exp' => 0,
                'ratio' => 1,
            );
        } else {
            for ($i = 0; $i < count($charm); $i++) {
                if ($exp < $charm[$i]) {
                    $num = $i;
                    break;
                }
            }
            $data = array(
                'exp' => $exp,
                'rank' => $num,
                'next_rank' => $num + 1,
                'differ_exp' => $charm[$num] - $exp,
                'ratio' => floor((($exp - $charm[$num - 1]) / ($charm[$num] - $charm[$num - 1])) * 100) / 100,
            );
        }
    }
    return $data ? $data : false;
}
/**
 * Notes: 过滤Emoji表情
 * User: 王俊成
 * Date: 2018/10/29
 * Time: 14:15
 * @param $str
 */
function filterEmoji($str){


    return  preg_replace_callback('/@E(.{6}==)/', function ($r) {
        return base64_decode($r[1]);
    }, $str);

//    for($i=0;$i<strlen($str);$i++){
//        if($str[$i] == '=') $str[$i] = '';  //替换'='
//    }
//
//    //处理表情字符串
//    $str = preg_replace_callback(
//        '/./u',
//        function (array $match) {
//            return strlen($match[0]) >= 4 ? '' : $match[0];
//        },
//        $str);
//
//
//    return $str;
}

/**
 * Notes: 转换带emoji表情的用户名或者签名
 * User: 王俊成
 * Date: 2018/10/30
 * Time: 10:56
 * @param $name
 * @return null|string|string[]
 */
function conversionEmojiName($name){
    return preg_replace_callback('/@E(.{6}==)/', function($r) {return base64_decode($r[1]);},$name);
}
/**
 * 简单对称加密算法之加密
 * @param String $string 需要加密的字串
 * @param String $skey 加密EKY
 * @author yaopengfei
 * @date 2013-08-13 19:30
 * @update 2014-10-10 10:10
 * @return String
 */
function encode($string = '', $skey = 'feiwenyuliaokaihei') {
    $strArr = str_split(base64_encode($string));
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
        $key < $strCount && $strArr[$key].=$value;
    return str_replace(array('=', '+', '/'), array('O0O0O', 'o000o', 'oo00o'), join('', $strArr));
}
/**
 * 简单对称加密算法之解密
 * @param String $string 需要解密的字串
 * @param String $skey 解密KEY
 * @author yaopengfei
 * @date 2013-08-13 19:30
 * @update 2014-10-10 10:10
 * @return String
 */
function decode($string = '', $skey = 'feiwenyuliaokaihei') {
    $strArr = str_split(str_replace(array('O0O0O', 'o000o', 'oo00o'), array('=', '+', '/'), $string), 2);
    $strCount = count($strArr);
    foreach (str_split($skey) as $key => $value)
        $key <= $strCount && $strArr[$key][1] === $value && $strArr[$key] = $strArr[$key][0];
    return base64_decode(join('', $strArr));
}

/**
 * @param $user_id,用户id
 * @param int $status 进账or出账
 * @param int $type 类型,关联钻石类型表
 * @param $number ,涉及数量
 * @return bool
 */
function DiamondsAccount($user_id,$status=1,$type=1,$number,$mark){

    $check_type = \app\admin\model\DiamondsType::where('id = '.$type)->find();
    if(!isset($check_type) || empty($check_type)){
        return true;
    }

    $user = \app\admin\model\User::where('id = '.$user_id)->field('id,u_id,nickname')->find();
    if(!isset($user) || empty($user)){
        return true;
    }
    $user['nickname'] = preg_replace_callback('/@E(.{6}==)/', function ($r) {
        return base64_decode($r[1]);
    }, $user['nickname']);

    $status_name = [
        1=>'获得了',
        2=>'消耗了'
    ];

    $content = '用户 ID : '.$user['id'].' U_ID : '.$user['id'].' nickname : '.$user['nickname'].' 于 '.date('Y-m-d H:i:s').' 经过'.$check_type['content'].'【'.$status_name[$status].'】了'.$number.$mark;

    $newData = [
        'user_id' => $user_id,
        'account_status' => $status,
        'type_id' => $type,
        'account_number' => $number,
        'content' => $content,
        'create_time' => time(),

    ];
    \app\admin\model\DiamondsAccount::create($newData);


    return true;
}


//聊天室发送消息
function sendAttachMsg($roomid, $fromAccid, $attach, $msgId = '', $msgType = 100)
{
    $AppKey = config('app.WyYx.AppKey');
    $AppSecret = config('app.WyYx.AppSecret');
    $p = new \app\common\api\ServerAPI($AppKey, $AppSecret, 'curl');
    $msgId = (string)(time() . rand(1000, 9999));
    $msgType = 100;
    $result = $p->sendAttachRoomMsg($roomid, $fromAccid, $attach, $msgId, $msgType);
    return $result;
}

/**
* Notes: 友盟全体广播
* User: Administrator
* Date: 2019\03\11 0003
* Time: 14:15
* @param $content
* @return bool
    * @throws Exception
*/
function sendUPushBroadcast($content, $extra = '', $type = 1)
{
    if (empty($content)) {
        return false;
    }
    $upush = new think\upush\UPush();
    $title = '绯闻语音';
    if ($type == 3) {
        $a = $upush->sendAndroidBroadcast($title, $content, $extra);
    } elseif ($type == 2) {
        $a = $upush->sendIOSBroadcast($content, $extra);
    } else {
        $a = $upush->sendAndroidBroadcast($title, $content, $extra);
        $a = $upush->sendIOSBroadcast($content, $extra);
    }
    $a = json_decode($a, true);
    if ($a['ret'] == 'SUCCESS') {
        return true;
    } else {
        return false;
    }
}
//会长二维码
//function get_QR_Code($unionInfo)
//{
//    include './../vendor/phpqrcode/phpqrcode.php';
//    $rcode = new QRcode();
//    //$value = "https://test.yuliaokaihei.com/Api/Public/regist/introduce_code/$spread_number";//二维码内容
//    $value = "https://api.quniuyuyin.com/Qq/UnionLogin/login?union_id=".$unionInfo['id'];//二维码内容
//    $errorCorrectionLevel = 'M';//容错级别
//    $matrixPointSize = 20;//生成图片大小
//    //生成二维码图片
//    //QRcode::png($value, './qr_code/'.$unionInfo['user_id'].'.png', $errorCorrectionLevel, $matrixPointSize, 4);
//    QRcode::png($value, './qr_code/test.png', $errorCorrectionLevel, $matrixPointSize, 4);
//
//    //$logo = $unionInfo['pic'] ? $unionInfo['pic'] : './qr_code/logo.png' ;
//   $logo = './qr_code/logo.png';//准备好的logo图片
//   // $QR = './qr_code/' .  $unionInfo['user_id'] . '.png'; //已经生成的原始二维码图
//    $QR = './qr_code/test.png'; //已经生成的原始二维码图
//
//    if ($logo !== FALSE) {
//        $QR = imagecreatefromstring(file_get_contents($QR));
//        $logo = imagecreatefromstring(file_get_contents($logo));
//        if (imageistruecolor($logo)) {
//            imagetruecolortopalette($logo, false, 65535);//添加这行代码来解决颜色失真问题
//        }
//        $QR_width = imagesx($QR);//二维码图片宽度
//        $QR_height = imagesy($QR);//二维码图片高度
//        $logo_width = imagesx($logo);//logo图片宽度
//        $logo_height = imagesy($logo);//logo图片高度
//        if ($logo_height > $logo_width) {
//            $logo_height = $logo_width;
//        }
//        $logo_qr_width = $QR_width / 5;
//        $scale = $logo_width / $logo_qr_width;
//        $logo_qr_height = $logo_height / $scale;
//        $from_width = ($QR_width - $logo_qr_width) / 2;
//        //重新组合图片并调整大小
//        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
//            $logo_qr_height, $logo_width, $logo_height);
//    }
//
//
////    $str = $unionInfo['name'];
////    //$img = imagecreatefrompng($QR);
////    $img = imagecreatefromstring(file_get_contents($QR));
////    $size =40;
////    $angle = 0;
////    $fontfile = './font_style.ttf';
////    $info = imagettfbbox($size,$angle,$fontfile,$str);
////    //var_dump($info);
////    $x = (imagesx($img) - ($info[4] - $info[6]))/2;
////    $y = imagesy($img) - 10;
////    $color = imagecolorallocate($img,255,0,0);
////
////    imagettftext($img,$size,$angle,$x,$y,$color,$fontfile,$str);
//    //输出图片
//    Header("Content-type: image/png");
//    return ImagePng($QR,'./qr_code/'.$unionInfo['name'].'.png');
//
//}

//生成共会二维码
function get_QR_Code($unionInfo)
{
    include './../vendor/phpqrcode/phpqrcode.php';
    $rcode = new QRcode();
    //$value = "https://test.yuliaokaihei.com/Api/Public/regist/introduce_code/$spread_number";//二维码内容
    $value = "https://api.quniuyuyin.com/Qq/UnionLogin/login?union_id=".$unionInfo['id'];//二维码内容
    $errorCorrectionLevel = 'M';//容错级别
    $matrixPointSize = 20;//生成图片大小
    //生成二维码图片
    QRcode::png($value, './qr_code/' . $unionInfo['user_id'] . '.png', $errorCorrectionLevel, $matrixPointSize, 4);

    $logo = $unionInfo['pic'] ? $unionInfo['pic'] : './qr_code/logo.png' ;
//   $logo = './qr_code/logo.png';//准备好的logo图片
    $QR = './qr_code/' . $unionInfo['user_id'] . '.png'; //已经生成的原始二维码图
    if ($logo !== FALSE) {
        $QR = imagecreatefromstring(file_get_contents($QR));

        $logo = imagecreatefromstring(file_get_contents($logo));
        if (imageistruecolor($logo)) {
            imagetruecolortopalette($logo, false, 65535);//添加这行代码来解决颜色失真问题
        }
        $QR_width = imagesx($QR);//二维码图片宽度
        $QR_height = imagesy($QR);//二维码图片高度
        $logo_width = imagesx($logo);//logo图片宽度
        $logo_height = imagesy($logo);//logo图片高度
        if ($logo_height > $logo_width) {
            $logo_height = $logo_width;
        }
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        //重新组合图片并调整大小
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width,
            $logo_qr_height, $logo_width, $logo_height);
    }
    //输出图片
    Header("Content-type: image/png");
    return ImagePng($QR,'./qr_code/'.$unionInfo['id'].'.png');
}
//共会添加文字二维码
//function add_ch_QR_Code($unionInfo)
//{
//
//    $str = $unionInfo['name'];
//
//    $QR = './qr_code/' . $unionInfo['name'] . '.png'; //已经生成的原始二维码图
//   // $img = imagecreatefromstring(file_get_contents($QR));
//    $img = imagecreatefrompng($QR);
//    $size =40;
//    $angle = 0;
//    $fontfile = './font_style.ttf';
//    $info = imagettfbbox($size,$angle,$fontfile,$str);
//    //var_dump($info);
//    $x = (imagesx($img) - ($info[4] - $info[6]))/2;
//    $y = imagesy($img) - 10;
//    $color = imagecolorallocate($img,255,0,0);
//
//    imagettftext($img,$size,$angle,$x,$y,$color,$fontfile,$str);
//    //输出图片
//    Header("Content-type: image/png");
//    return ImagePng($QR,'./qr_code/'.$unionInfo['name'].'.png');
//}

function add_ch_QR_Code($unionInfo)
{
    $size = 60;
    $fontfile = './font_style.ttf';

    $str = $unionInfo['name'];
    //创建一个长为500高为80的空白图片
    // $img = imagecreate(500, 80);
    $QR = './qr_code/' . $unionInfo['id'] . '.png'; //已经生成的原始二维码图
    // $img = imagecreatefromstring(file_get_contents($QR));
    $img = imagecreatefrompng($QR);
    //给图片分配颜色
    // imagecolorallocate($img, 0xff, 0xcc, 0xcc);

    //将ttf文字写到图片中
    $angle = 0;
    $info = imagettfbbox($size,$angle,$fontfile,$str);
    $x = (imagesx($img) - ($info[4] - $info[6]))/2;
    $y = imagesy($img) - 10;
    //设置字体颜色
    $color = imagecolorallocate($img,0,0,0);
    imagettftext($img,$size,$angle,$x,$y,$color,$fontfile,$str);

    //发送头信息
    header('Content-Type: image/png');
    //输出图片
    // ImagePNG($img);
    //保存图片至指定路径
    ImagePNG($img, './qr_code/'.$unionInfo['name'] .'.png');
    imagedestroy($img);

}

//操作日志
function dailyLog($arr){
    $DailyLog = new \app\admin\model\DailyLog();
    $arr['admin_id'] = session('admin_id');
    $DailyLog->save($arr);
    return true;

}